# =========== 导入组件 ============
from rest_framework import serializers
# =========== 导入数据类 ============
from useweb.models import Position, Staff, Roles, Permission, Button, RolesPermission,RolesPermissonDetail
from basicweb.models import AreaPlace
# =========== 引入其他app中的序列化类 =============
from basicweb.serializer import AreaPlaceSerializer


# 场地类型
class PositionSerializer(serializers.ModelSerializer):
    class Meta:
        model =Position
        fields = "__all__"


# 按钮
class ButtonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Button
        fields = "__all__"


# 任务类行
class StaffSerializer(serializers.ModelSerializer):
    position = PositionSerializer()
    areaplace = AreaPlaceSerializer(many=True, read_only=True)
    placecode = serializers.SerializerMethodField() # 这个字段的值由后续的方法填充
    roles = serializers.SerializerMethodField()
    last_login = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    edit_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model =Staff
        fields = "__all__"
        # fields = ('id', 'name','position','mobile','email','status', 'areaplace','pa')

    # 命名的规则：get_属性名
    # obj -- 当前的对象
    def get_placecode(self, obj):
        # 获取所有场地的信息
        placelist = AreaPlace.objects.filter(staff=obj)
        # 定义code集合
        code_list = []
        # 遍历获取的集合
        for item in placelist:
            code_list.append(item.code)
        # 返回
        return ",".join(code_list)

    def get_roles(self,obj):
        # 获取所有的角色信息
        roles_list = Roles.objects.filter(staff=obj)
        # 定义角色id
        roles_id_list = []
        # 遍历
        for item in roles_list:
            roles_id_list.append(item.id)
        # 返回
        return roles_id_list


# 任务状态
class RolesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Roles
        fields = "__all__"


# 权限条目
class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = "__all__"


# 角色权限明细
class RolesPermissionDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = RolesPermissonDetail
        fields = "__all__"
